require "rjb"
#require 'parseexcel'
#require 'spreadsheet/excel'
#include Spreadsheet

class ReportsController < ApplicationController
  before_filter :user_authorize
  layout "index" ,:except => [:dailySellReport,:reportByType,:dailySellReportWin,:integrationSellReport,
    :airwaysSellReport,:airportsSellReport,:reportByIntegrattion,:reportByAirports,:reportByAirways,:salesReport,
    :createSalesReport]
  def businessReports
    
  end
  
  def reports
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  def reportByType
    begin
      report_type = params[:report_type_value]
      #logger.error report_type
      endDate = params[:dateend]
      beginDate = params[:datebegin]
      if report_type == "dailysellreport"
        report_file_name = dailySellReport(beginDate,endDate)
        #logger.error report_file_name
        if report_file_name != nil
          report_path = "<a href='/reports/#{report_file_name}' target='_blank'>销售日报表下载</a>"
          jsonstr=report_path
          render :text=>jsonstr, :layout=>false
        else
          report_path = "没有相关数据以生成销售日报表</a>"
          jsonstr=report_path
          render :text=>jsonstr, :layout=>false
        end
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #综合日销售报表
  def reportByIntegrattion
    begin
      #logger.error report_type
      endDate = params[:dateend]
      beginDate = params[:datebegin]
      report_file_name = dailySellReport(beginDate,endDate,"Integrattion")
      #logger.error report_file_name
      if report_file_name != nil
        report_path = "<a href='/reports/#{report_file_name}' target='_blank'>综合销售日报表下载</a>"
        jsonstr=report_path
        render :text=>jsonstr, :layout=>false
      else
        report_path = "没有相关数据以生成综合销售日报表</a>"
        jsonstr=report_path
        render :text=>jsonstr, :layout=>false
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #按航空公司制作报表
  def reportByAirways
    begin
      #logger.error report_type
      airway_code=params[:airways_code]
      endDate = params[:airways_dateend]
      beginDate = params[:airways_datebegin]
      report_file_name = dailySellReport(beginDate,endDate,"Airways",airway_code)
      #logger.error report_file_name
      if report_file_name != nil
        report_path = "<a href='/reports/#{report_file_name}' target='_blank'>按航空公司统计 销售日报表下载</a>"
        jsonstr=report_path
        render :text=>jsonstr, :layout=>false
      else
        report_path = "没有相关数据以生成 按航空公司统计 销售日报表下载</a>"
        jsonstr=report_path
        render :text=>jsonstr, :layout=>false
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #按航线统计
  def reportByAirports
    airport_code_to = params[:airport_code_to]
    airport_code_from = params[:airport_code_from]
    begin
      #logger.error report_type
      endDate = params[:airports_dateend]
      beginDate = params[:airports_datebegin]
      report_file_name = dailySellReport(beginDate,endDate,"Airports",airport_code_from+airport_code_to)
      #logger.error report_file_name
      if report_file_name != nil
        report_path = "<a href='/reports/#{report_file_name}' target='_blank'>按航空公司统计 销售日报表下载</a>"
        jsonstr=report_path
        render :text=>jsonstr, :layout=>false
      else
        report_path = "没有相关数据以生成 按航空公司统计 销售日报表下载</a>"
        jsonstr=report_path
        render :text=>jsonstr, :layout=>false
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #birthdayKey.split("-")[0]
  def dailySellReport(beginDate,endDate,reportType,reportParameters)
    logger.error reportParameters
    begin
      excel = Rjb::import("JavaExcel").new()
      orders = nil
      if reportType=="Integrattion"
        orders = Order.find(:all,:conditions=>["is_locked <> 1 AND (created_at between ? AND ? ) AND status = ?",beginDate,endDate,Constants::ORDER_STATUS_YCP], :include => "tickets")
      elsif reportType == "Airways" 
        orders = Order.find(:all,:conditions=>["is_locked <> 1 AND (created_at between ? AND ? ) AND status = ? AND airNo like ?",beginDate,endDate,Constants::ORDER_STATUS_YCP,"%#{reportParameters}%"], :include => "tickets")
      elsif reportType == "Airports"
        orders = Order.find(:all,:conditions=>["is_locked <> 1 AND (created_at between ? AND ? ) AND status = ? AND fromto like ?",beginDate,endDate,Constants::ORDER_STATUS_YCP,"%#{reportParameters}%"], :include => "tickets")
      end
      #created_at status="" Constants::ORDER_STATUS_YCP
      #logger.error orders.length
      tickets_length_total = 0
      if orders.length>0
        excel.importExcel("#{RAILS_ROOT}/report_template/dailysellreport.xls")
        orders.length.times do |i|
          tickets = orders[i].tickets
          tickets_length_current = tickets.length
          tickets_length_current.times do |j|
            rowNumber = tickets_length_total+j+1
            excel.excelWrite(0,rowNumber,1,tickets[j].ticket_no.to_s,"String")
            excel.excelWrite(0,rowNumber,2,tickets[j].air_no.to_s,"String")
            excel.excelWrite(0,rowNumber,3,tickets[j].fromto.to_s,"String")
            excel.excelWrite(0,rowNumber,4,tickets[j].position.to_s,"String")
            excel.excelWrite(0,rowNumber,5,tickets[j].price.to_s,"String")
            excel.excelWrite(0,rowNumber,6,tickets[j].fly_date.to_s,"String")
          end
          tickets_length_total = tickets_length_total + tickets_length_current
        end
        reportFileName="#{reportType}-dailysellreport#{beginDate}-#{endDate}.xls"
        #logger.error "#{RAILS_ROOT}/public/reports/#{reportFileName}"
        excel.exportExcel("#{Rails.public_path}/reports/#{reportFileName}")
        reportFileName
      else
        nil
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
    #redirect_to("#{request.relative_url_root}/reports/test1.xls")
    #redirect_to("#{request.relative_url_root}/reports/test1.xls")
    #redirect_to("/reports/test1.xls")
    #    logger.error params
    #    @report_path="<a href='/reports/test1.xls'>报表下载</a>"
    #    jsonstr="<a href='/reports/test1.xls' target='_blank'>销售日报表下载</a>"
    #    render :text=>jsonstr, :layout=>false
    #"/reports/test1.xls"
  end
  
  def integrationSellReport
  end
  
  def airwaysSellReport
    logger.error "airwaysSellReport"
  end
  
  def salesReport
  end
  
  def createSalesReport
    begin
      #报表参数类别
      searchType = params[:search_type]
      dateBegin = params[:search_date_begin]
      dateEnd = params[:search_date_end]
      dateEnd = (dateEnd.to_date+1).to_s
      airwayscode = params[:airwayscode]
      fromAirportCode = params[:from_airport_code]
      toAirportCode = params[:to_airport_code]
      fromto = "#{fromAirportCode}#{toAirportCode}"
      if searchType == "time"
        tickets = Ticket.find(:all,:conditions=>["is_locked <> 1 AND (created_at between ? AND ? )",dateBegin,dateEnd])
      elsif searchType == "airways" 
        tickets = Ticket.find(:all,:conditions=>["is_locked <> 1 AND (created_at between ? AND ? ) AND airNo like ?",dateBegin,dateEnd,"%#{airwayscode}%"])
      elsif searchType == "fromto"
        tickets = Ticket.find(:all,:conditions=>["is_locked <> 1 AND (created_at between ? AND ? ) AND fromto like ?",dateBegin,dateEnd,"%#{fromto}%"])
      end
      #created_at status="" Constants::ORDER_STATUS_YCP
      excel = Rjb::import("JavaExcel").new()
      rowNumber = 0
      if tickets.length>0
        excel.importExcel("#{RAILS_ROOT}/report_template/sales_report.xls")
        tickets.length.times do |i|
          excel.excelWrite(0,i+3,1,tickets[i].ticket_no.to_s,"String")
          excel.excelWrite(0,i+3,2,tickets[i].air_no.to_s,"String")
          excel.excelWrite(0,i+3,3,tickets[i].fromto.to_s,"String")
          excel.excelWrite(0,i+3,4,tickets[i].position.to_s,"String")
          excel.excelWrite(0,i+3,5,tickets[i].price.to_s,"Double")
          excel.excelWrite(0,i+3,6,tickets[i].fly_date.to_s,"String")
          excel.excelWrite(0,i+3,7,tickets[i].rake_off.to_s,"Double")
          payment = tickets[i].price*(100-tickets[i].rake_off)*0.01
          excel.excelWrite(0,i+3,8,payment.to_s,"Double")
          tax = tickets[i].fuel_tax + tickets[i].airdrome_tax
          excel.excelWrite(0,i+3,9,tax.to_s,"Double")
          excel.excelWrite(0,i+3,10,(payment+tax).to_s,"Double")
        end
        reportFileName = "#{searchType}-SalesReport#{dateBegin}-#{dateEnd}.xls"
        #logger.error "#{RAILS_ROOT}/public/reports/#{reportFileName}"
        excel.exportExcel("#{RAILS_ROOT}/public/reports/#{reportFileName}")
        report_path = "<a href='/reports/#{reportFileName}' target='_blank'>销售报表下载</a>"
        jsonstr="{success:true,info:'报表成功',path:\"#{report_path}\"}"
        render :text=>jsonstr, :layout=>false
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
end
